package com.zhanglijie.theory.readwrite;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/8/14 0014 16:04
 */
public class MyReadWriteLock {
    //正在读的线程数
    private int readingReaders = 0;
    //正在写的线程数
    private int writingWriters = 0;

    private boolean preferWriter = true;
        private int waitingWriter = 0;

    /**
     * 读锁加锁
     */
    public synchronized void readLock() throws InterruptedException {
        //第二个条件保证写优先
        while(writingWriters > 0 || (preferWriter && waitingWriter>0)){
            wait();
        }
        readingReaders++;
    }

    /**
     * 读锁解锁
     */
    public synchronized void readUnLock(){
        readingReaders--;
        preferWriter = true;
        notifyAll();
    }

    /**
     * 写锁加锁
     */
    public synchronized void writeLock() throws InterruptedException {
        waitingWriter ++;
        try {
            while (readingReaders > 0 || writingWriters > 0) {
                wait();
            }
        }finally {
            waitingWriter --;
        }
        writingWriters ++;
    }

    /**
     * 写锁解锁
     */
    public synchronized void writeUnLock(){
        writingWriters --;
        preferWriter = false;
        notifyAll();
    }
}
